<?php
/**
 * Created by PhpStorm.
 * User: 曹乐清
 * Date: 2017/4/20
 * Time: 16:49
 */

namespace Api\Controller;


use Think\Controller;
use Think\JSSDK;
use Think\WeChatApi;

require_once './ThinkPHP/Library/Vendor/WxpayApi/lib/WxPay.Config.php';

define('Token','E763C76214D27CB0F886E177C296C6EF');
class ContactController extends Controller
{
    private $app_id='';//这里声明
    private $app_secret='';
    public function _initialize(){
        $wxConfig=new \WxPayConfig();
        $this->app_id=$wxConfig::APPID;
        $this->app_secret=$wxConfig::APPSECRET;

    }
    public function index()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $echostr = $_GET['echostr'];
        $token = Token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature && $echostr) {
            echo $echostr;
            exit;
        } else {
            $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

            if (!empty($postStr)) {
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $RX_TYPE = trim($postObj->MsgType);
                $api = new WeChatApi($this->app_id, $this->app_secret);
                switch ($RX_TYPE) {
                    case "text"://接收文本消息
                        $data = M('wechat_response')->select();
                        $resultStr = $api->receiveText($postObj, $data);
                        break;
                    case "image"://接收图片
                        $resultStr = $api->receiveImage($postObj);
                        break;
                    case "location"://位置消息
                        $resultStr = $api->receiveLocation($postObj);
                        break;
                    case "voice"://接收语音
                        $resultStr = $api->receiveVoice($postObj);
                        break;
                    case "video": //接收视频
                        $resultStr = $api->receiveVideo($postObj);
                        break;
                    case "link"://链接消息
                        $resultStr = $api->receiveLink($postObj);
                        break;
                    case "event": //接收事件，关注等
                        $data = M('wechat_create_menu')->select();

                        $resultStr = $api->receiveEvent($postObj, $data);
                        break;
                    default:
                        $resultStr = "unknow msg type: " . $RX_TYPE;
                        break;
                }
                echo $resultStr;
            } else {
                echo "";
                exit;
            }
        }
    }
}